#!/usr/bin/perl
use strict;
use Getopt::Long;
use Data::Dumper;
use File::Path;
use DBI;
use Backup::Read;

my $dbiUsername = "";
my $dbiPassword = "";
my $dbiHost = "";
my $dbiSocket = "";

my $backupFolder = "";
# If user wants to specify other options
GetOptions('u:s'=>\$dbiUsername,
	'p:s'=>\$dbiPassword,
	'h:s'=>\$dbiHost,
	's:s'=>\$dbiSocket,
	'd:s'=>\$backupFolder);

if ( $> != 0 ) {
	print STDERR "You must be root to run this program\n";
	exit;
}

my $dbh = DBI->connect("DBI:mysql:information_schema;host=$dbiHost;socket=$dbiSocket;",$dbiUsername,$dbiPassword);
opendir(DIR,$backupFolder) or die ("Error when trying to open backup folder: $!\n");
my @directory = readdir(DIR);
closedir(DIR);
my @backups = ();
foreach (@directory) {
	if ( -d "$backupFolder/$_" && -f "$backupFolder/$_/backup.ini" &&!($_ =~ /\.$/)) {
		push (@backups, $_);
	}
}
my $backup = menu("Choose a backup:",0,@backups);
print "Reading database structure file...\n";
my $back = Backup::Read->new("$backupFolder/$backups[$backup]");
my $ini = $back->getINI();
my $selectedBackup = $backups[$backup];
my @databases = ("Restore All Databases",keys %$ini);
my @database = menu("Choose a database to restore:",1,@databases);
my $choiceCount = scalar @database;
if ( $database[0] == 0 ) {
	#restore all databases with default settings
	print "Extracting and building queries... ";
	foreach (keys %$ini) {
		$back->addDatabase($_);
	}
	$back->cleanup();
	print "Done.\n";
} elsif ( $choiceCount == 1 ) {
	#show options for 1 database
	my $databaseChoice = menu("Database Option",0,("Restore this database","Restore this database to a different database","View tables"));
	if ( $databaseChoice == 0 ) {
		print "Extracting and building queries... ";
		$back->addDatabase($databases[$database[0]]);
		$back->cleanup();
		print "Done.\n";
	} elsif ( $databaseChoice == 1 ) {
		print "Enter the name of the database you wish to restore to: ";
		my $to = <STDIN>;
		$to =~ s/\n$//;
		print "Extracting and building queries... ";
		$back->addDatabase($databases[$database[0]],$to);
		$back->cleanup();
		print "Done.\n";
	} elsif ( $databaseChoice == 2 ) {
		#Display all tables
		my @tableOptions = @{$ini->{$databases[$database[0]]}};
		my @tableChoices = menu("Choose tables you which to run commands on:",1,@tableOptions);
		my $tableCommandChoice = menu("Choose which command you want to run",0,("Restore table(s)","Restore table(s) to a different database","Restore table(s) to a different database under a different name"));
		if ( $tableCommandChoice == 0 ) {
			#Restore all tables chosen
			print "Extracting and building queries... ";
			foreach (@tableChoices) {
				$back->addTable($databases[$database[0]],undef,$tableOptions[$_]);
			}
			$back->cleanup();
			print "Done.\n";		
		} elsif ( $tableCommandChoice == 1 ) {
			print "Enter the name of the database you wish to restore to: ";
			my $to = <STDIN>;
			$to =~ s/\n$//;
			print "Extracting and building queries... ";
			foreach (@tableChoices) {
				$back->addTable($databases[$database[0]],$to,$tableOptions[$_]);
			}
			$back->cleanup();
			print "Done.\n";
		} elsif ( $tableCommandChoice == 2 ) {
			print "Enter the name of the database you wish to restore to: ";
			my $to = <STDIN>;
			$to =~ s/\n$//;
			my $tableRename = {};
			foreach (@tableChoices) {
				print "Enter the name of the table you wish to restore table $tableOptions[$_] to: ";
				my $tableInput = <STDIN>;
				$tableInput =~ s/\n$//;
				$tableRename->{$tableOptions[$_]} = $tableInput;	
			}
			print "Extracting and building queries... ";
			foreach (@tableChoices) {
				$back->addTable($databases[$database[0]],$to,$tableOptions[$_],$tableRename->{$tableOptions[$_]});
			}
			$back->cleanup();
			print "Done.\n";
		}
	} else {
		exit;
	}
} else {
	#restore multiple databases with default settings
	print "Extracing and building queries... ";
	foreach (@database) {
		$back->addDatabase($databases[$_]);
		$back->cleanup();
	}
	print "Done.\n";
}

open(FILE_W,">query.txt");
print FILE_W $back->getQuery();
close(FILE_W);
print "Restoring... ";
system("mysql -u $dbiUsername -p$dbiPassword -h $dbiHost < query.txt");
print "Done.\n";
system("rm -f query.txt");

sub menu {
	# This is a helper subroutine to build simple menus
	my($question,$multipleOptions,@options) = @_;
	print "---$question---\n";
	my $i = 1;
	my $numOptions = @options;
	foreach (@options) {
		print "${i}. $_\n";
		$i++;
	}
	if ( $multipleOptions ) {
		print "Pick an option(multiple choices seperated by one space): ";
		my $option = <STDIN>;
		$option =~ s/\n$//;
		my @choices = split(/[ ]/,$option);
		my $x = 0;
		foreach (@choices) {
			if ( !(int($_)>=1 && int($_)<=$numOptions) ) {
				print "Please pick only options given\n";
				return menu($question,$multipleOptions,@options);
			}
			$choices[$x] = int($_)-1;
			$x++;
		}
		return sort(@choices);
	} else {
		print "Pick an option: ";
		my $option = <STDIN>;
		$option =~ s/\n$//;
		if ( !(int($option)>=1 && int($option)<=$numOptions) ) {
			print "Please pick only options given\n";
			return menu($question,$multipleOptions,@options);
		}
		return int($option)-1;
	}
}
	
